package com.boonya.spring.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @ClassName: TransactionTemplateExample
 * @Description: TODO(功能说明 : 事务管理)
 * @author: pengjunlin
 * @motto: 学习需要毅力，那就秀毅力
 * @date 2021/3/28 11:45
 */
@Component
public class TransactionTemplateExample {
    @Autowired
    DataSource dataSource;
    @Autowired
    TransactionManager transactionManager;
    @Autowired
    TransactionTemplate transactionTemplate;

    /**
     * 编程式事务
     *
     * @param sql
     */
    public void execute(final String sql) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                Connection connection = DataSourceUtils.getConnection(dataSource);
                try {
                    Statement st = connection.createStatement();
                    Boolean flag = st.execute(sql);
                    System.out.println("操作成功!");
                    return flag;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}
